package com.example.springbook.Controller;
import com.example.springbook.constant.Constants;
import com.example.springbook.model.*;
import com.example.springbook.service.BookService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private  BookService bookService;
    @RequestMapping(value = "/addBook", produces = "application/json")
    public String addBook(BookInfo bookInfo){
        log.info("添加图书，接受到参数bookInfo：{}"+bookInfo);
        if(!StringUtils.hasLength(bookInfo.getBookName())||!StringUtils.hasLength(bookInfo.getAuthor())
        ||bookInfo.getCount()==null
        ||bookInfo.getPrice()==null
        ||!StringUtils.hasLength(bookInfo.getPublish())
        ||bookInfo.getStatus()==null){
            return "参数不合法";
        }
        try {
            Integer result= bookService.insertBook(bookInfo);
            if(result>0){
                return "";
            }
        }catch (Exception e){
            log.error("图书添加异常，e:",e);
        }
        return "添加失败";
    }
    @RequestMapping("/getBookListBypage")
    public Result<PageResult<BookInfo>> getBookListBypage(PageRequest pageRequest, HttpSession session){
        //参数校验
//        UserInfo loginuserInfo=(UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);
//        Result result=new Result();
//        if (loginuserInfo==null||loginuserInfo.getId()<0){
//            return Result.nologin();
//        }
        log.info("查询图书列表, 请求参数pageRequest: {}", pageRequest);
       PageResult<BookInfo> bookList =bookService.getBookListBypage(pageRequest);
        return Result.success(bookList);
    }
    /*
    * 更新图书
    * */
    @RequestMapping("/getBookById")
    public BookInfo getBookById(Integer bookId){
        log.info("id为: "+bookId);
        return bookService.getBookById(bookId);

    }
    @RequestMapping(value = "/updateBook", produces = "application/json")
    public String updateBook(BookInfo bookInfo){
        return bookService.updateBook(bookInfo);
    }
    @RequestMapping(value = "/deleteBook", produces = "application/json")
    public String deleteBook(BookInfo bookInfo){
        return bookService.deleteBook(bookInfo);
    }
    @RequestMapping(value = "/batchDeleteBookByIds", produces = "application/json")
    public String batchDeleteBookByIds(@RequestParam List<Integer> ids){
        log.info("ids:{}"+ids);
        return bookService.batchDeleteBookByIds(ids);
    }


}
